package com.yangxc.core.datasource.provider;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.druid.DruidConfig;
import com.yangxc.core.datasource.properties.DataSourceProperties;
import com.yangxc.core.datasource.support.DataSourceConstants;
import org.jasypt.encryption.StringEncryptor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangxc
 * @version 1.0.0
 * @ClassName JdbcDynamicDataSourceProvider.java
 * @Description 从数据库中读取数据源配置信息
 * @createTime 2021年07月22日 09:32:00
 */
public class JdbcDynamicDataSourceProvider extends AbstractJdbcDataSourceProvider {

    private final DataSourceProperties dataSourceProperties;

    private final StringEncryptor stringEncryptor;


    public JdbcDynamicDataSourceProvider(DataSourceProperties dataSourceProperties,StringEncryptor stringEncryptor) {
        super(dataSourceProperties.getDriverClassName(), dataSourceProperties.getUrl()
                , dataSourceProperties.getUsername(), dataSourceProperties.getPassword());
        this.dataSourceProperties = dataSourceProperties;
        this.stringEncryptor = stringEncryptor;
    }

    @Override
    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
        ResultSet rs = statement.executeQuery(dataSourceProperties.getQueryDsSql());

        Map<String, DataSourceProperty> map = new HashMap<>(8);
        while (rs.next()) {
            String name = rs.getString(DataSourceConstants.NAME);
            String username = rs.getString(DataSourceConstants.USERNAME);
            String password = rs.getString(DataSourceConstants.PASSWORD);
            String url = rs.getString(DataSourceConstants.URL);
            String druidConfigStr = rs.getString(DataSourceConstants.DRUID_CONFIG);

            DataSourceProperty property = new DataSourceProperty();
            property.setUsername(username);
            property.setPassword(stringEncryptor.decrypt(password));
            property.setUrl(url);

            DruidConfig druidConfig = JSONObject.parseObject(druidConfigStr, DruidConfig.class);
            property.setDruid(druidConfig);
            map.put(name, property);
        }

        // 添加默认主数据源
        DataSourceProperty property = new DataSourceProperty();
        property.setUsername(dataSourceProperties.getUsername());
        property.setPassword(dataSourceProperties.getPassword());
        property.setUrl(dataSourceProperties.getUrl());
        map.put(DataSourceConstants.DS_MASTER, property);
        return map;
    }
}
